//
//  HLVideoCacheController.m
//  HLAerospace
//
//  Created by hulian-ios on 17/9/16.
//  Copyright © 2017年 hulian-LB. All rights reserved.
//

#import "HLVideoCacheController.h"
#import "HLDownLoaderManager.h"
#import "HLDownLoader.h"
#import "HLDownLoadingCell.h"
#import "HLDownLoadedCell.h"
#import "HLCourseDetail.h"
#import "HLDataBaseManager.h"
#import "NSString+DownLoader.h"
#import "MBProgressHUD+HL.h"
#import "HLCourseDetailViewController.h"
#import "HLFoldCourse.h"
#import "HLArticleViewController.h"
#import "ReaderViewController.h"

@interface HLVideoCacheController ()<UITableViewDelegate,UITableViewDataSource,HLDownLoadingCellDelegate,HLDownLoadedCellDelegate,ReaderViewControllerDelegate>

@property (nonatomic ,strong) UITableView *tableView;
/** 数据源  */
@property (nonatomic ,strong) NSMutableArray *downLoadingSource;
/** 数据源  */
@property (nonatomic ,strong) NSMutableArray *downLoadedSource;

@property (nonatomic ,weak) NSTimer *timer;
@end

@implementation HLVideoCacheController


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self setUI];
    
    NSTimer *timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(configUI) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop]addTimer:timer forMode:NSRunLoopCommonModes];
    self.timer = timer;
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(back) name:UIApplicationDidEnterBackgroundNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(reloadTableView) name:kHLDownLoadTableViewReloadDataNotifacation object:nil];
}

- (void)back
{
    [[HLDownLoaderManager shareInstance] pauseAll];
    NSArray *detailCourses =  [HLDataBaseManager downloadingFiles:1];
    for (HLCourseDetail *detail in detailCourses) {
        detail.isPauseState = YES;
        [HLDataBaseManager updateDownloadingFile:detail];
        [self.tableView reloadData];
    }
}

- (void)reloadTableView
{
    [self.tableView reloadData];
}

- (void)configUI
{
    NSArray *a = [HLDataBaseManager downloadingFiles:1];
    if (a.count == 0) {
        [self.timer invalidate];
        [self.tableView reloadData];
        return;
    }
    
    for (HLCourseDetail *detail in a) {
        NSInteger index =  [a indexOfObject:detail];
        HLDownLoader *downloader;
        @synchronized (self) {
            downloader =[HLDownLoaderManager shareInstance].downLoadInfo[[detail.play_url md5]];
        }
        HLDownLoadingCell *downLoadingCell= [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
        downLoadingCell.progressView.progress = downloader.progress;
        downLoadingCell.contentNum.text = [NSString stringWithFormat:@"%@/%@",[self fileSize:detail.totalSize * downloader.progress],[self fileSize:detail.totalSize]];
    }
}


- (void)setUI
{
    self.navigationItem.title = @"离线缓存";
    self.tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:1];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = HLRGB(245, 245, 245);
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.rowHeight = IS_IPHONE_5 ? 75: 80 ;
    [_tableView registerClass:[HLDownLoadingCell class] forCellReuseIdentifier:@"HLDownLoadingCell"];
    [_tableView registerClass:[HLDownLoadedCell class] forCellReuseIdentifier:@"HLDownLoadedCell"];
    [self.view addSubview:_tableView];
}


- (NSString *)fileSize:(long long )fileSize
{
    /*** 计算缓存大小 ***/
    NSInteger size = fileSize;
    CGFloat unit = 1000.0;
    NSString *sizeText = nil;
    if (size >= unit * unit * unit) { // >= 1GB
        sizeText = [NSString stringWithFormat:@"%.1fGB", size / unit / unit / unit];
    } else if (size >= unit * unit) { // >= 1MB
        sizeText = [NSString stringWithFormat:@"%.1fMB", size / unit / unit];
    } else if (size >= unit) { // >= 1KB
        sizeText = [NSString stringWithFormat:@"%.1fKB", size / unit];
    } else { // >= 0B
        sizeText = [NSString stringWithFormat:@"%zdB", size];
    }
    return sizeText;
}

#pragma mark - UITableViewDelegate,UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return section == 0 ? [HLDataBaseManager downloadingFiles:1].count: [HLDataBaseManager downloadedFiles:1].count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray * downLoading = [HLDataBaseManager downloadingFiles:1];
    NSArray * downLoaded = [HLDataBaseManager downloadedFiles:1];
    HLDownLoadingCell *downLoadingCell = [tableView dequeueReusableCellWithIdentifier:@"HLDownLoadingCell"];
    downLoadingCell.delegate = self;
    HLDownLoadedCell *downLoadiedCell = [tableView dequeueReusableCellWithIdentifier:@"HLDownLoadedCell"];
    downLoadiedCell.delegate = self;
    if (indexPath.section == 0) {
        if (downLoading.count > 0) {
            downLoadingCell.courseDetail = downLoading[indexPath.row];
        }
    }
    if (indexPath.section == 1) {
        if (downLoaded.count > 0) {
            downLoadiedCell.courseDetail = downLoaded[indexPath.row];
        }
    }
    return indexPath.section == 0 ? downLoadingCell  :downLoadiedCell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSArray *titles = @[@"正在下载",@"已下载"];
    NSArray *allOperationTitles = @[@"全部暂停",@"全部删除"];
    UIView *headerView = [UIView new];
    headerView.height = 50;
    headerView.backgroundColor = [UIColor whiteColor];
    UILabel *title = [UILabel new];
    title.text = titles[section];
    title.frame = CGRectMake(10, 10, 100, 30);
    [headerView addSubview:title];
    
    UIButton *allOperation = [UIButton new];
    allOperation.tag = section;
    allOperation.layer.cornerRadius = 3;
    allOperation.clipsToBounds = YES;
    allOperation.titleLabel.font = [UIFont systemFontOfSize:13];
    allOperation.frame = CGRectMake(ScreenWidth - 80, 12.5, 70, 25);
    allOperation.backgroundColor = HLRGB(200, 200, 200);
    [allOperation setTitleColor:HLRGB(30, 30, 30) forState:UIControlStateNormal];
    [allOperation setTitle:allOperationTitles[section] forState:UIControlStateNormal];
    [allOperation addTarget:self action:@selector(allOperationClick:) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:allOperation];
    
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 50;
}

#pragma mark - HLDownLoadingCellDelegate

- (void)downLoadingCell:(HLDownLoadingCell *)downLoadingCell didClickPauseCourseDetail:(HLCourseDetail *)courseDetail
{
    HLDownLoader *downloader = [HLDownLoaderManager shareInstance].downLoadInfo[[courseDetail.play_url md5]];
    [HLDataBaseManager updateDownloadingFile:courseDetail];
    if (courseDetail.isPauseState) {
        [downloader pauseCurrentTask];
    }else{
        [downloader resumeCurrentTask];
    }
}

- (void)downLoadingCell:(HLDownLoadingCell *)downLoadingCell didClickDeleteCourseDetail:(HLCourseDetail *)courseDetail
{
    NSString *file = [@"/tmp" stringByAppendingPathComponent:[NSURL URLWithString:courseDetail.play_url].lastPathComponent];
    [[NSFileManager defaultManager]removeItemAtPath:[NSHomeDirectory() stringByAppendingPathComponent:file] error:nil];
    [HLDataBaseManager removeDownloadingFile:courseDetail];
    [self.tableView reloadData];
}

#pragma mark - HLDownLoadedCellDelegate
- (void)downLoadedCell:(HLDownLoadedCell *)downLoadedCell didClickDeleteCourseDetail:(HLCourseDetail *)courseDetail
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示"message:@"真的要删除这条数据吗?" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"想好了" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        /**** 删除数据 ****/
        
        NSError *error;
        [[NSFileManager defaultManager]removeItemAtPath:courseDetail.filePath error:&error];
        if (error) {
            NSLog(@"删除单一文件失败");
        }
        [HLDataBaseManager removeDownloadedFile:courseDetail];
        [self.tableView reloadData];
        
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alertController animated:YES completion:nil];

}

- (void)downLoadedCell:(HLDownLoadedCell *)downLoadedCell didClickPlayCourseDetail:(HLCourseDetail *)courseDetail
{
    if([courseDetail.favourate_state integerValue] == 1){
        HLCourseDetailViewController *couseDetailVC = [HLCourseDetailViewController new];
        couseDetailVC.isSkipFormHistoryRecord = YES;
        couseDetailVC.courseDetail = courseDetail;
        [self.navigationController pushViewController:couseDetailVC animated:YES];
    }
    if([courseDetail.favourate_state integerValue] == 2){
        
        ReaderDocument *doc = [[ReaderDocument alloc] initWithFilePath:courseDetail.filePath password:nil];
        ReaderViewController *rederVC = [[ReaderViewController alloc] initWithReaderDocument:doc];
        rederVC.delegate = self;
        [self presentViewController:rederVC animated:YES completion:nil];
    }
}

- (void)dismissReaderViewController:(ReaderViewController *)viewController
{
    [self dismissViewControllerAnimated:YES completion:nil];
}


- (void)allOperationClick:(UIButton *)button
{
    /**** 全部暂停 ****/
    if (button.tag == 0) {
        [[HLDownLoaderManager shareInstance] pauseAll];
        NSArray *detailCourses =  [HLDataBaseManager downloadingFiles:1];
        for (HLCourseDetail *detail in detailCourses) {
            detail.isPauseState = YES;
            [HLDataBaseManager updateDownloadingFile:detail];
            [self.tableView reloadData];
        }
        
    }
    /**** 全部删除 ****/
    if (button.tag == 1) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示"message:@"真的要删除全部数据吗?" preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"想好了" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            
            /**** 删除全部数据 ****/
            [[NSFileManager defaultManager] removeItemAtPath:HLCacheFile error:nil];
            [HLDataBaseManager removeALLDownloadedFile];
            [self.tableView reloadData];
            
        }]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    [self.timer invalidate];
    self.timer = nil;
    NSLog(@"销毁了%@",[self class]);
}





@end
